package com.cze.dao.impl;

import com.cze.dao.PersonDAO;
import com.cze.vo.Person;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class PersonDAOImpl implements PersonDAO {
    private JdbcTemplate jdbcTemplate;

    @Resource(name = "jdbcTemplate")
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public int add(Person person) {
        Object[] obj = new Object[]{person.getId(),person.getName(),person.getPassword()};
        try{
            return jdbcTemplate.update("insert into person(id, name, password) VALUES (?,?,?)", obj);
        }catch (DuplicateKeyException e){
            System.out.println(e.getMessage());
            return 0;
        }

    }

    @Override
    public int delete(String personID) {
        return jdbcTemplate.update("delete from person where id=?", personID);
    }

    @Override
    public int update(Person person) {
        Object[] obj = new Object[]{person.getName(),person.getPassword(),person.getId()};
        return jdbcTemplate.update("update person set name=?,password=? where id=?",
                                    obj);
    }

    @Override
    public Person findByID(String personID) {
        try{
            return jdbcTemplate.queryForObject("select * from person where id=?",
                    new BeanPropertyRowMapper<Person>(Person.class),
                    personID);
        }catch (EmptyResultDataAccessException e){
            System.out.println(e.getMessage());
            return null;
        }
    }
}
